package club.zhcs.task.job;

import org.nutz.dao.Dao;
import org.nutz.http.Request;
import org.nutz.http.Request.METHOD;
import org.nutz.http.Response;
import org.nutz.http.sender.PostSender;
import org.nutz.ioc.Ioc;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.mvc.Mvcs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import club.zhcs.task.bean.Task;
import club.zhcs.task.bean.TaskDetail;
import club.zhcs.task.bean.TaskDetail.Status;
import club.zhcs.task.dao.ITaskDetailDao;

public class CommonJob implements Job {

	@Override
	public void execute(JobExecutionContext CommonJob) throws JobExecutionException {
		System.err.println("running...");
		Task task = (Task) CommonJob.getMergedJobDataMap().get("task");
		ITaskDetailDao taskDetailDao = (ITaskDetailDao) CommonJob.getMergedJobDataMap().get("taskDetailDao");
		
		TaskDetail detail = new TaskDetail();
		detail.setStartTime(Times.now());
		detail.setTaskId(task.getId());
		taskDetailDao.save(detail);// 开始调用保存记录
		
		Request request = Request.create(task.getInvokeUrl(), METHOD.POST);
		PostSender sender = new PostSender(request);
		Response response = sender.send();
		
		if (response.getStatus() == 200 && Strings.equals(response.getContent(), "ok")) {// 成功
			detail.setStatus(Status.DONE);
			detail.setDoneTime(Times.now());
			taskDetailDao.update(detail);
		} else {
			detail.setStatus(Status.FAIL);//失败
			detail.setFailTime(Times.now());
			detail.setMessage(response.getContent());
			taskDetailDao.update(detail);
		}
	}

	protected Dao getDao() {
		return getIocObj("dao", Dao.class);
	}

	protected <T> T getIocObj(String name, Class<T> clazzOfK) {
		return getIoc().get(clazzOfK, name);
	}

	protected Ioc getIoc() {
		return Mvcs.getIoc();
	}

}
